sed命令

sed命令是利用脚本来处理文本文件,可依照脚本的指令来处理、编辑文本文件,主要用来自动编辑一个或多个文件、简化对文件的反复操作、编写转换程序等。

语法

sed [OPTION]... {script-only-if-no-other-script} [input-file]...

参数

示例

file.txt文件内容如下。

unix is great os. unix is opensource. unix is free os.
learn operating system.
unix linux which one you choose.
unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

将文件中的每行的第一个单词unix替换为linux,要保存的话需要使用输出重定向。

sed "s/unix/linux/" file.txt

# linux is great os. unix is opensource. unix is free os.
# learn operating system.
# linux linux which one you choose.
# linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

替换行中模式的第2个匹配项,将行中出现的第二个单词unix替换为linux

sed "s/unix/linux/2" file.txt

# unix is great os. linux is opensource. unix is free os.
# learn operating system.
# unix linux which one you choose.
# unix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful.

使用替换标志/g全局替换指定sed命令来替换行中所有出现的字符串。

sed "s/unix/linux/g" file.txt

# linux is great os. linux is opensource. linux is free os.
# learn operating system.
# linux linux which one you choose.
# linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.

指定第2个之后的全部匹配模式的字符进行替换。

sed "s/unix/linux/2g" file.txt

# unix is great os. linux is opensource. linux is free os.
# learn operating system.
# unix linux which one you choose.
# unix is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful

用括号括住每个单词的第一个字符,在括号中打印每个单词的第一个字符。

echo "Welcome To The World" | sed "s/\(\b[A-Z]\)/\(\1\)/g"

# (W)elcome (T)o (T)he (W)orld

可以限制sed命令替换特定行号上的字符串。

sed "3 s/unix/linux/g" file.txt

# unix is great os. unix is opensource. unix is free os.
# learn operating system.
# linux linux which one you choose.
# unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

参考

https://www.computerhope.com/unix/used.htm
https://www.runoob.com/linux/linux-comm-sed.html
https://www.geeksforgeeks.org/sed-command-in-linux-unix-with-examples/